# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
uuid    = require 'uuid'
router = express.Router()
module.exports = router

router.get '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select * from pay_o_091 limit 1", defer err, result
    if err then done(client); return next(err)

    # 如果还没有配置，则自动生成默认配置
    if result.rows.length == 0
        await client.query \
            "insert into pay_o_091 (
                uuid, remote_addr, remote_port, timeout,
                remote_addr2, remote_port2, tpdu, notes
            ) values (
                $1, '', 0, 30, '', 0, '', 'POS 009.1 接出服务'
            )", [
                uuid.v4()
            ], defer err, result
        if err then done(client); return next(err)
        done()
        return res.redirect '/o/091'
    else
        done()
        return res.render 'o/091', record: result.rows[0]


router.post '/edit', (req, res, next) ->
    for k in ['uuid', 'remote_addr', 'remote_port', 'timeout']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update pay_o_091 set
            remote_addr = $1, remote_port = $2, timeout = $3,
            remote_addr2 = $4, remote_port2 = $5, tpdu = $6,
            notes = $7
            where uuid = $8", [
            req.body.remote_addr,
            parseInt(req.body.remote_port),
            parseInt(req.body.timeout),
            req.body.remote_addr2,
            parseInt(req.body.remote_port2) or 0,
            req.body.tpdu,
            req.body.notes,
            req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/o/091'


router.post '/disable', (req, res, next) ->
    res.type('json')
    for k in ['uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update pay_o_091 set disabled = $1 where uuid = $2", [
            req.body.disabled, req.body.uuid,
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.json succ: true, redirect: '/o/091'
